package com.ricky.order.api;

import com.ricky.common_util.result.Result;
import com.ricky.order.service.PaymentService;
import com.ricky.order.service.WxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Api(tags = "微信支付接口")
@RestController
@RequestMapping("/api/order/weixin")
public class WxController {
    @Autowired
    private WxService wxService;
    @Autowired
    private PaymentService paymentService;

    @ApiOperation("生成微信支付二维码")
    @GetMapping("createNative/{orderId}")
    public Result createNative (@PathVariable Long orderId){
        Map map = wxService.createNative(orderId);
        return Result.ok(map);
    }

    @ApiOperation("查询订单支付的状态")
    @GetMapping("queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable Long orderId){
        // 调用微信接口，实现支付状态查询
        Map<String,String> resultMap = wxService.queryPayStatus(orderId);
        //判断支付状态
        if (resultMap == null) {
            return Result.fail().message("支付出错");
        }
        if ("SUCCESS".equals(resultMap.get("trade_state"))){
            // 更新订单状态
            String outTradeNo = resultMap.get("out_trade_no"); //订单编码
            paymentService.paySuccess(outTradeNo,resultMap);
            return Result.ok().message("支付成功");

        }
        return Result.ok().message("支付中...");
    }
}
